package com.example.demoserver.controller;

import com.example.demoserver.entity.HousePart;
import com.example.demoserver.entity.HousePartsInfo;
import com.example.demoserver.entity.HousePartstore;
import com.example.demoserver.entity.HouseProduct;
import com.example.demoserver.service.impl.HousePartServiceImpl;
import com.example.demoserver.service.impl.HouseProductServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/part")
@RequiredArgsConstructor
@Component
public class partController {
    private final HousePartServiceImpl housePartService;
    private final HouseProductServiceImpl houseProductService;
    @PostMapping("/insertpart")
    public boolean insertPart(@RequestBody List<HousePartstore> housePartstores) {
        List<HousePart> list=new ArrayList<>();
        for (HousePartstore h: housePartstores) {
            HousePart housePart=new HousePart();
            housePart.setPartbatch(getTime(1)+h.getId());
            housePart.setBuytime(getTime(2));
            housePart.setStoreid(h.getId().toString());
            list.add(housePart);
        }
        boolean bol=housePartService.saveBatch(list);
        return bol;
    }
    @GetMapping("/selectpart")
    public List<HousePartsInfo> selectPart() {
        List<HousePartsInfo> list =housePartService.selectAll();
        return list;
    }
    @GetMapping("/getpart")
    public List<HousePartsInfo> getPart(String proId) {
        HouseProduct houseProduct=houseProductService.selectByProId(proId);
        String[] idList=houseProduct.getPartid().split(",");
        List<HousePartsInfo> list=new ArrayList<>();
        for (int i = 0; i < idList.length; i++) {
            if(idList[i]!=""){
                HousePartsInfo housePartsInfo=housePartService.selectInfoById(idList[i]);
                list.add(housePartsInfo);
            }

        }
        return list;
    }
    public String getTime(int type){
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter;
        String formattedDate;
        if(type==1){
            formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            formattedDate = currentDateTime.format(formatter);
        }else{
            formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            formattedDate  = currentDateTime.format(formatter);
        }
        return formattedDate;
    }

}
